package com.basic;

import java.util.ArrayList;
import java.util.Iterator;

public class Market {
	private static Market uniqueInstance = new Market();
	private ArrayList<Good> goods;
	
	Market(){
		goods = new ArrayList<Good>();
	}
	
	public static Market getInstance(){
		return uniqueInstance;
	}
	
	public void addGood(Good good){
		this.goods.add(good);
	}
	
	public Good returnGoodAt(int n){
		return this.goods.get(n);
	}
	
	/**Returns the price of the most
	 * expensive good
	 * */
	public double mostExpensiveGood(){
		Iterator<Good> it = this.goods.iterator();
		double mostExp = 0;
		while(it.hasNext()){
			Good g = (Good)it.next();
			double current = g.getValue();
			if(current > mostExp){
				mostExp = current;
			}
		}
		return mostExp;
	}
	
	/**Returns the value of the least expensive
	 * Good.*/
	public double leastExpensiveGood(){
		Iterator<Good> it = this.goods.iterator();
		double leastExp = this.goods.get(0).getValue();
		while(it.hasNext()){
			Good g = (Good)it.next();
			double current = g.getValue();
			if(current < leastExp){
				leastExp = current;
			}
		}
		
		return leastExp;
	}
	
	public void sellGood(int n){
		this.goods.remove(n);
	}
	
	public MarketHelper sellGoodByCost(double cost){
		//Could use a location and count and do this in
		//one loop I think.
		
		//update count on each iteration if availbleCost is
		//updated add count to location then set count to 0;
		//int location = 0;
		double availableCost = 0.0;
		Iterator <Good> it = this.goods.iterator();
		while(it.hasNext()){
			Good g = (Good)it.next();
			if(g.getValue() <= cost && g.getValue() >= availableCost){
				availableCost = g.getValue();
			}
		}
		Iterator<Good> it2 = this.goods.iterator();
		int count = 0;
		while(it2.hasNext()){
			
			if(((Good)it2.next()).getValue() == availableCost){
				System.out.println("count: " + count);
				return new MarketHelper(count, availableCost);
			}
			count++;
		}
		return new MarketHelper(-1, -1);
	}
	public void removeGood(int n){
		System.out.println("n=" + n);
		this.goods.remove(n);
		
	}
	public void listAll(){
		Iterator <Good> it = this.goods.iterator();
		while(it.hasNext()){
			System.out.println(((Good)it.next()).getValue());
		}
	}

}
